﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace OALPTool
{
    public partial class FrmColStyleSet : Form
    {

        #region 成员变量

        /// <summary>
        /// 需要隐藏/显示列的DataGridView
        /// </summary>
        public DataGridView m_dgvC;
        /// <summary>
        /// DataGridView列属性组织的DataTable
        /// </summary>
        DataTable dtList = null;
        /// <summary>
        /// DataGridView数据源
        /// </summary>
        DataView m_dv = new DataView();
        /// <summary>
        /// DataGridView样式
        /// </summary>
        ArrayList m_colList = new ArrayList();

        private string refreshflag = "";
        #endregion

        public FrmColStyleSet()
        {
            InitializeComponent();
        }

        public int InitForm(DataGridView dgvC)
        {
            this.m_dgvC = dgvC;
            this.refreshflag = "0";

            dtList = new DataTable();
            dtList.Columns.Add("sortno", typeof(int));
            dtList.Columns.Add("name",typeof(string));
            dtList.Columns.Add("chnname", typeof(string));
            dtList.Columns.Add("width",typeof(int));
            dtList.Columns.Add("isvisible", typeof(string));

            //根据DataGridView的列显示顺序号生成DataTable绑定到dgv上
            for (int i = 0; i < dgvC.Columns.Count; i++)
            {
                for (int j = 0; j < dgvC.Columns.Count; j++)
                {
                    if (dgvC.Columns[j].DisplayIndex == i)
                    {
                        DataRow drnew = dtList.NewRow();
                        drnew["sortno"] = i + 1;
                        drnew["name"] = dgvC.Columns[j].Name;
                        drnew["chnname"] = dgvC.Columns[j].HeaderText;
                        drnew["width"] = dgvC.Columns[j].Width;
                        if (dgvC.Columns[j].Visible)
                            drnew["isvisible"] = "是";
                        else drnew["isvisible"] = "否";
                        dtList.Rows.Add(drnew);
                        break;
                    }
                }
            }

            dtList.DefaultView.Sort = "sortno";
            //设置dgv样式
            this.SetDgvStyle(dtList.DefaultView);

            this.dgv.AllowUserToAddRows = false;
            this.dgv.AllowUserToDeleteRows = false;

            return 0;
        }

        public int InitForm(DataGridView dgvC, string dgvName)
        {
            if (dgvName == null || dgvName.Trim() == "")
            {
                this.Text = "格式设置";
            }
            else
            {
                this.Text = dgvName;
            }

            this.m_dgvC = dgvC;
            this.refreshflag = "0";

            dtList = new DataTable();
            dtList.Columns.Add("sortno", typeof(int));
            dtList.Columns.Add("name", typeof(string));
            dtList.Columns.Add("chnname", typeof(string));
            dtList.Columns.Add("width", typeof(int));
            dtList.Columns.Add("isvisible", typeof(string));

            //根据DataGridView的列显示顺序号生成DataTable绑定到dgv上
            for (int i = 0; i < dgvC.Columns.Count; i++)
            {
                for (int j = 0; j < dgvC.Columns.Count; j++)
                {
                    if (dgvC.Columns[j].DisplayIndex == i)
                    {
                        DataRow drnew = dtList.NewRow();
                        drnew["sortno"] = i + 1;
                        drnew["name"] = dgvC.Columns[j].Name;
                        drnew["chnname"] = dgvC.Columns[j].HeaderText;
                        drnew["width"] = dgvC.Columns[j].Width;
                        if (dgvC.Columns[j].Visible)
                            drnew["isvisible"] = "是";
                        else drnew["isvisible"] = "否";
                        dtList.Rows.Add(drnew);
                        break;
                    }
                }
            }

            dtList.DefaultView.Sort = "sortno";
            //设置dgv样式
            this.SetDgvStyle(dtList.DefaultView);

            this.dgv.AllowUserToAddRows = false;
            this.dgv.AllowUserToDeleteRows = false;

            return 0;
        }

        public int InitFormRefresh(DataGridView dgvC, ArrayList colList, DataView dv, string dgvName)
        {
            if (dgvName == null || dgvName.Trim() == "")
            {
                this.Text = "格式设置";
            }
            else
            {
                this.Text = dgvName;
            }

            this.m_dgvC = dgvC;
            this.m_colList = colList;
            this.m_dv = dv;
            this.refreshflag = "1";

            dtList = new DataTable();
            dtList.Columns.Add("sortno", typeof(int));
            dtList.Columns.Add("name", typeof(string));
            dtList.Columns.Add("chnname", typeof(string));
            dtList.Columns.Add("width", typeof(int));
            dtList.Columns.Add("isvisible", typeof(string));

            //根据DataGridView的列显示顺序号生成DataTable绑定到dgv上
            for (int i = 0; i < dgvC.Columns.Count; i++)
            {
                DataRow drnew = dtList.NewRow();
                drnew["sortno"] = i + 1;
                drnew["name"] = dgvC.Columns[i].Name;
                drnew["chnname"] = dgvC.Columns[i].HeaderText;
                drnew["width"] = dgvC.Columns[i].Width;
                if (dgvC.Columns[i].Visible)
                    drnew["isvisible"] = "是";
                else drnew["isvisible"] = "否";
                dtList.Rows.Add(drnew);
            }

            dtList.DefaultView.Sort = "sortno";
            //设置dgv样式
            this.SetDgvStyle(dtList.DefaultView);

            this.dgv.AllowUserToAddRows = false;
            this.dgv.AllowUserToDeleteRows = false;

            return 0;
        }

        private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == this.tbbExit)
            {
                this.Close();
            }
            else if (e.ClickedItem == this.tbbUp)
            {
                if (!this.Validate()) return;

                this.dgv_Row_Up();
            }
            else if (e.ClickedItem == this.tbbDown)
            {
                if (!this.Validate()) return;

                this.dgv_Row_Down();
            }
            else if (e.ClickedItem == this.tbbOK)
            {
                if (!this.Validate()) return;

                //设置dgv焦点到第一行第一列，使得更改的显示隐藏CheckBox值生效
                if (this.dgv.Rows.Count > 0 && this.dgv.Rows[0].Cells.Count > 0)
                    this.dgv.CurrentCell = this.dgv.Rows[0].Cells[0];

                dgv_StyleChange();
            }
        }


        private void dgv_StyleChange() 
        {
            if (this.refreshflag == "1")
            {
                DataView dv = dtList.DefaultView;
                dv.Sort = "sortno";

                ArrayList colListNew = new ArrayList();
                //循环DataTable，更改colList
                for (int i = 0; i < dv.Count; i++)
                {
                    string colname = dv[i]["name"].ToString();

                    foreach (object o in this.m_colList) 
                    {
                        object[] obj = (object[])o;
                        if (obj[1].ToString().Equals(colname)) 
                        {
                            obj[3] = Convert.ToInt32(dv[i]["width"].ToString());
                            obj[9] = Convert.ToInt32(dv[i]["sortno"].ToString());
                            colListNew.Add(obj);
                            break;
                        }
                    }

                }

                DataGridViewFunc.setDgvStyle(colListNew, ref this.m_dgvC, this.m_dv);

                for (int i = 0; i < dv.Count; i++)
                {
                    string colname = dv[i]["name"].ToString();

                    if (dv[i]["isvisible"].ToString() == "是")
                    {
                        this.m_dgvC.Columns[colname].Visible = true;
                    }
                    else
                    {
                        this.m_dgvC.Columns[colname].Visible = false;
                    }
                }

                this.DialogResult = DialogResult.OK;
            }
            else 
            {
                DataView dv = dtList.DefaultView;
                dv.Sort = "sortno";

                //循环DataTable，更改DataGridView列的Visiable,Width和DisplayIndex属性
                for (int i = 0; i < dv.Count; i++)
                {
                    string colname = dv[i]["name"].ToString();

                    if (dv[i]["isvisible"].ToString() == "是")
                    {
                        this.m_dgvC.Columns[colname].Visible = true;
                    }
                    else
                    {
                        this.m_dgvC.Columns[colname].Visible = false;
                    }
                    this.m_dgvC.Columns[colname].Width = Convert.ToInt32(dv[i]["width"].ToString());
                    this.m_dgvC.Columns[colname].DisplayIndex = Convert.ToInt32(dv[i]["sortno"].ToString()) - 1;
                }

                this.DialogResult = DialogResult.OK;
            }
        }

        /// <summary>
        /// 上移事件
        /// </summary>
        private void dgv_Row_Up() 
        {
            if (this.dgv.CurrentRow == null)
            {
                return;
            }
            else if (this.dgv.CurrentRow.Index == 0)
            {
                return;
            }
            else
            {
                dtList.DefaultView.Sort = "sortno";

                int currow = this.dgv.CurrentRow.Index;

                //移除需要移动的当前行
                int iSortNo = Convert.ToInt32(dtList.Rows[currow]["sortno"].ToString());
                string strName = dtList.Rows[currow]["name"].ToString();
                string strChName = dtList.Rows[currow]["chnname"].ToString();
                string strWidth = dtList.Rows[currow]["width"].ToString();
                string strIsVisible = dtList.Rows[currow]["isvisible"].ToString();
                
                //更改上一行的SortNo
                dtList.Rows[currow - 1]["sortno"] = iSortNo;
                dtList.Rows.RemoveAt(currow);

                //将删除的行插入到DataTable上一行前
                DataRow cur_dr = dtList.NewRow();
                cur_dr["sortno"] = iSortNo - 1;
                cur_dr["name"] = strName;
                cur_dr["chnname"] = strChName;
                cur_dr["width"] = strWidth;
                cur_dr["isvisible"] = strIsVisible;

                dtList.Rows.InsertAt(cur_dr, currow - 1);
                dtList.AcceptChanges();

                //重新设置dgv样式
                this.SetDgvStyle(dtList.DefaultView);

                //设置dgv焦点到刚移动过的行上
                this.dgv.ClearSelection();

                if (this.dgv.Rows.Count != 0 && this.dgv.Columns.Count != 0)
                {
                    this.dgv.Rows[currow - 1].Selected = true;
                    this.dgv.CurrentCell = this.dgv.Rows[currow - 1].Cells[0];
                }
            }
        }


        /// <summary>
        /// 下移事件
        /// </summary>
        private void dgv_Row_Down() 
        {
            if (this.dgv.CurrentCell == null)
            {
                return;
            }
            else if (this.dgv.CurrentRow.Index == this.dgv.Rows.Count - 1)
            {
                return;
            }
            else
            {
                dtList.DefaultView.Sort = "sortno";

                int currow = this.dgv.CurrentRow.Index;

                //移除需要移动的当前行
                int iSortNo = Convert.ToInt32(dtList.Rows[currow]["sortno"].ToString());
                string strName = dtList.Rows[currow]["name"].ToString();
                string strChName = dtList.Rows[currow]["chnname"].ToString();
                string strWidth = dtList.Rows[currow]["width"].ToString();
                string strIsVisible = dtList.Rows[currow]["isvisible"].ToString();

                //更改下一行的SortNo
                dtList.Rows[currow+1]["sortno"] = iSortNo;
                dtList.Rows.RemoveAt(currow);

                //将删除的行插入到DataTable下一行后
                DataRow cur_dr = dtList.NewRow();
                cur_dr["sortno"] = iSortNo + 1;
                cur_dr["name"] = strName;
                cur_dr["chnname"] = strChName;
                cur_dr["width"] = strWidth;
                cur_dr["isvisible"] = strIsVisible;

                dtList.Rows.InsertAt(cur_dr, currow + 1);
                dtList.AcceptChanges();

                //重新设置dgv样式
                this.SetDgvStyle(dtList.DefaultView);

                //设置dgv焦点到刚移动过的行上
                this.dgv.ClearSelection();

                if (this.dgv.Rows.Count != 0 && this.dgv.Columns.Count != 0)
                {
                    this.dgv.Rows[currow + 1].Selected = true;
                    this.dgv.CurrentCell = this.dgv.Rows[currow + 1].Cells[0];
                }
            }
        }

        /// <summary>
        /// 设置dgv样式
        /// </summary>
        /// <param name="dv">dgv绑定数据源</param>
        private void SetDgvStyle(DataView dv) 
        {
            ArrayList collist = new ArrayList();
            collist.Add(new object[] { "列名", "chnname", "0", 200, null, DataGridViewContentAlignment.MiddleCenter, true, "", null, 1, "", "", "", "", "" });
            collist.Add(new object[] { "宽度", "width", "0", 80, null, DataGridViewContentAlignment.MiddleRight, false, "", null, 2, "", "", "", "", "" });
            collist.Add(new object[] { "是否显示", "isvisible", "1", 100, null, DataGridViewContentAlignment.MiddleCenter, false, "", null, 3, "", "", "", "", "" });

            DataGridViewFunc.setDgvStyle(collist, ref this.dgv, dv);
        }

        /// <summary>
        /// 设置行号
        /// </summary>
        private void dgv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewFunc.disDgvSerialno(this.dgv, e);
        }


        private void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (this.dgv.Columns[e.ColumnIndex].Name == "width")
            {
                if (e.FormattedValue.ToString() == String.Empty || e.FormattedValue.ToString().Trim() == "")
                {
                    TSysPublic.ShowMsg("宽度不能为空！");
                    this.dgv.Rows[e.RowIndex].ErrorText = "宽度不能为空！";
                    e.Cancel = true;
                }
                else
                {
                    string pat = @"^[0-9]*[1-9][0-9]*$";
                    Regex r = new Regex(pat, RegexOptions.Compiled);
                    Match m = r.Match(e.FormattedValue.ToString());

                    if (!m.Success)
                    {
                        TSysPublic.ShowMsg("宽度只能为大于0的整数！");
                        this.dgv.Rows[e.RowIndex].ErrorText = "宽度只能为大于0的整数！";
                        e.Cancel = true;
                    }
                    else if (e.FormattedValue.ToString().Length > 3) 
                    {
                        TSysPublic.ShowMsg("宽度只能为小于1000的整数！");
                        this.dgv.Rows[e.RowIndex].ErrorText = "宽度只能为小于1000的整数！";
                        e.Cancel = true;
                    }
                    else
                    {
                        this.dgv.Rows[e.RowIndex].ErrorText = "";
                        e.Cancel = false;
                    }
                }
            }
        }
    }
}
